#! python3
# time模块

import time


def baseDemo():
    """
    time模块基本功能演示
    :return:
    """
    print('UNIX 纪元时间戳:', time.time())  # UNIX 纪元时间戳

    # 获取当前时间元组
    localtime = time.localtime()
    # localtime = time.localtime(time.time())
    print("UNIX 纪元时间戳  转换为 时间元组:", localtime)
    print(localtime.tm_year)

    asctime = time.asctime(localtime)
    print("本地时间为 :", asctime)

    # 格式化成2016-03-20 11:45:39形式
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    # 格式化成Sat Mar 28 22:24:24 2016形式
    print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))

    # 将格式字符串转换为时间戳
    a = "Sat Mar 28 22:24:24 2016"
    print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))

    # time.sleep()  单位：秒
    # 不要用一次 time.sleep(30)调用来暂停 30 秒，
    # 而应该使用 for 循环执行 30 次 time.sleep(1)调用
    # for i in range(3):
    #     print('Tick', i)
    #     time.sleep(1)
    #     print('Tock', i)
    #     time.sleep(1)

    # 数字四舍五入
    now = time.time()
    print('四舍五入演示：', now, round(now, 2), round(now, 4), round(now), sep="\n")


def stopwatch():
    """
    项目：超级秒表
    :return:
    """
    try:
        print('Press ENTER to begin. Afterwards',
              'press ENTER to "click" the stopwatch',
              'Press Ctrl - C to quit.')
        input()  # press Enter to begin
        print('Started.')
        startTime = time.time()  # get the first lap's start time
        lastTime = startTime
        lapNum = 1
        while True:
            input()
            lapTime = round(time.time() - lastTime, 2)
            totalTime = round(time.time() - startTime, 2)
            print('Lap #%s: %s (%s)' % (
                str(lapNum).rjust(3, " "),
                str(totalTime).rjust(5, " "),
                str(lapTime).rjust(5, " ")), end='')
            lapNum += 1
            lastTime = time.time()  # reset the last lap time
    except KeyboardInterrupt:
        # Handle the Ctrl-C exception to keep its error message from displaying.
        print('\nDone.')


if __name__ == '__main__':
    baseDemo()
    # stopwatch()
